package com.chima.action;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import com.chima.domain.TastCenterOperationcount;
import com.chima.domain.TastCentercoffe;
import com.chima.domain.Taskcenterbouns;
import com.chima.domain.Taskcenterbounsstock;
import com.chima.service.TastCenterService;
import com.chima.utils.ExcelRead;
import com.chima.utils.ExcelRead2010;
import com.opensymphony.xwork2.ActionSupport;
import flexjson.JSONSerializer;
public class TastCenterAction extends ActionSupport{
	
	private TastCenterService tastCenterService;
	
	private ExcelRead excelRead;

	private ExcelRead2010 excelRead2010;

	private String searchdate;
	private int searchdepartment;
//	private boolean success=false;
	private File upload;
	private int department;
	public ExcelRead getExcelRead() {
		return excelRead;
	}

	public void setExcelRead(ExcelRead excelRead) {
		this.excelRead = excelRead;
	}

	public ExcelRead2010 getExcelRead2010() {
		return excelRead2010;
	}

	public void setExcelRead2010(ExcelRead2010 excelRead2010) {
		this.excelRead2010 = excelRead2010;
	}

	public int getDepartment() {
		return department;
	}

	public void setDepartment(int department) {
		this.department = department;
	}

	// 上传文件名
	private String uploadFileName;

	// 上传文件类型
	private String uploadContentType;
	private String ex;
	
	
	public String getEx() {
		return ex;
	}

	public void setEx(String ex) {
		this.ex = ex;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getSearchdate() {
		return searchdate;
	}

	public void setSearchdate(String searchdate) {
		this.searchdate = searchdate;
	}

	public int getSearchdepartment() {
		return searchdepartment;
	}

	public void setSearchdepartment(int searchdepartment) {
		this.searchdepartment = searchdepartment;
	}


	public void setTastCenterService(TastCenterService tastCenterService) {
		this.tastCenterService = tastCenterService;
	}

	public String  listSupplyroombouns() throws Exception{
		
		int worktotal=0;
		double costtotal=0.00;
		double bouns=0.00;
		if(searchdepartment!=0){
//			List<TastCenterOperationcount> Operationcounts=supplyroomService.findSupplyroomOperationcountByDate(searchdate.substring(0, 7));
			List<TastCenterOperationcount> Operationcounts=tastCenterService.findTastCenterOperationcountByDateAnddept(searchdate.substring(0, 7), searchdepartment);
			for(TastCenterOperationcount s:Operationcounts){
				worktotal+=s.getOperationcount();
				costtotal+=s.getOperationcount()*(tastCenterService.findTastCentercoffeById(s.getTastCentercoffe().getId()).getOperationCoeff());
			}
			Taskcenterbounsstock stock=tastCenterService.findTaskcenterbounsstockByDateAndDeptId(searchdate.substring(0, 4),searchdepartment);
			bouns=getTechnologyBonusByMethod(stock.getMethod(),costtotal,stock.getMonthcoststock(),stock.getWeightcoffe());
			tastCenterService.addOrModityTaskcenterbouns((bouns), (costtotal), (worktotal), searchdate.substring(0,7), searchdepartment);

		}
		
		return SUCCESS;
	}
	public String  listtaskCenterbouns() throws Exception{
			if(searchdate!=null && searchdepartment!=0){
				Taskcenterbouns Taskcenterbouns= tastCenterService.findTaskcenterbounsByDateAndDeptId(searchdate, searchdepartment);
				JSONSerializer jsonSerializer = new JSONSerializer();
		        jsonSerializer.exclude("*.class");
		        String resultJson1 = jsonSerializer.deepSerialize(Taskcenterbouns);  
		        String jsonString = "{Taskcenterbouns:"+resultJson1.toString()+"}";
				ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
				ServletActionContext.getResponse().getWriter().print(jsonString);
			}
		return NONE;
	}
	
	public double getTechnologyBonusByMethod(String method,double standData,double referenceData,double basePrice){
		double bonus=0;
		String[] p=method.split(",");
		for (int i = 0; i < p.length; i++) {
			String[] m=p[i].split(":");
			String[] c=m[0].split("-");
			if(c.length==2){
				if(standData/referenceData > Double.parseDouble(c[1])){
					bonus+=(Double.parseDouble(c[1])-Double.parseDouble(c[0]))*referenceData*Double.parseDouble(m[1])*basePrice;
				}else{
					bonus+=(standData-referenceData*Double.parseDouble(c[0]) )*Double.parseDouble(m[1])*basePrice;
					break;
				}
			}
		}
		return bonus;
	}
	
	public String uploadAndImportExcel() throws Exception  {
		
		   
		// 上传到服务器端upload固定文件中,文件 名改为test.xls
				ex=uploadFileName.substring(uploadFileName.indexOf(".")+1);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
				String someFileName = sdf.format(new Date()) + "post.xls";
				if (ex != null && ex.equals("xls")) {
					someFileName = sdf.format(new Date()) + "post.xls";
				} else if (ex != null && ex.equals("xlsx")) {
					someFileName = sdf.format(new Date()) + "post.xlsx";
				}
				String path = "/cache";
				try {
					// 路径upload创建,不存在就创建，存在就不创建
					String filePath = "/yyjs/cache";
					File file = new File(filePath);
					// 判断文件夹是否存在,如果不存在则创建文件夹
					if (!file.exists()) {
						file.mkdirs();
					// 创建文件夹，如果要创建文件：
						if (file.mkdir()) { 
							file.createNewFile();
						}
					}
				} catch (Exception e) {
				}
				path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath(path);
				BufferedInputStream is = new BufferedInputStream(new FileInputStream(upload));
				File f = new File(path, someFileName);
				BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(f));
				IOUtils.copy(is, os);
				is.close();
				os.close();
				
				// excel读取文件
				if (ex != null && ex.equals("xls")) {
					System.out.println(path + "\\" + someFileName);
					excelRead.importExcel(path + "\\" + someFileName);
				} else if (ex != null && ex.equals("xlsx")) {
					excelRead2010.importExcel(path + "\\" + someFileName);
				}
				
				List<List> lists = new ArrayList();
				List listoperation = new ArrayList();
				int rowcount = 0;
				if (ex != null && ex.equals("xls")) {
					rowcount = excelRead.getRowIndex(0);
				} else if (ex != null && ex.equals("xlsx")) {
					rowcount = excelRead2010.getRowIndex(0);
				}
				for (int i = 0; i <= rowcount; i++) {
					if (ex != null && ex.equals("xls")) {
						listoperation = excelRead.readRow(0, i);
					} else if (ex != null && ex.equals("xlsx")) {
						listoperation = excelRead2010.readRow(0, i);
					}
					lists.add(listoperation);
				}
				if(department!=0){
					String thisMonth = "";
					for (int i = 0; i <= rowcount; i++) {	
						if(i==0){
							thisMonth = (lists.get(i).get(1).toString().substring(lists.get(i).get(1).toString().indexOf(":")+1)).replace("/", "-");	
						}
						if(i>1){
							String operationName = lists.get(i).get(1).toString().trim();
							TastCentercoffe tastCentercoffe = tastCenterService.findTastCentercoffeByNameAnddept(operationName, department);
							for (int j = 1; j < lists.get(i).size(); j++) {
									if (lists.get(i).get(j) != null&& !lists.get(i).get(j).toString().equals("")) {
										String cellContent = lists.get(i).get(j).toString().trim();
//										tastCenterService.addOrModitySupplyroomOperationcount(operationName, (int) Double.parseDouble(cellContent), thisMonth, supplyroomcoffe.getId());
										tastCenterService.addOrModityTastCenterOperationcount(operationName, (int) Double.parseDouble(cellContent), thisMonth, tastCentercoffe.getId());
									}
							}
						
						}
					}
				}
				return SUCCESS;
		
	}
}
